import {useEffect, useState} from 'react'
import Taro from '@tarojs/taro'
import {CoverView, CoverImage} from '@tarojs/components'
import {tabBarStore} from "@/store/tabbar-store";
import './index.scss'

export default function CustomTabBar() {
	const [state, setState] = useState(tabBarStore.getState())

	useEffect(() => {
		// 订阅状态变化
		const unsubscribe = tabBarStore.subscribe(() => {
			setState(tabBarStore.getState())
		})

		// 初始化时同步路由
		const currentPages = Taro.getCurrentPages()
		if (currentPages.length > 0) {
			const currentRoute = currentPages[currentPages.length - 1].route
			const matchedIndex = state.list.findIndex(item =>
				item.pagePath === currentRoute || `/${item.pagePath}` === currentRoute
			)
			if (matchedIndex >= 0 && state.selected !== matchedIndex) {
				tabBarStore.setSelected(matchedIndex)
			}
		}

		return unsubscribe
	}, [state.list, state.selected])

	const switchTab = (index: number, url: string) => {
		const fullPath = url.startsWith('/') ? url : `/${url}`
		Taro.switchTab({url: fullPath}).then(() => {
			tabBarStore.setSelected(index)
		})
	}

	return (
		<CoverView className='tab-bar'>
			<CoverView className='tab-bar-border'></CoverView>
			{state.list.map((item, index) => (
				<CoverView key={index} className='tab-bar-item' onClick={() => switchTab(index, item.pagePath)}>
					<CoverImage src={state.selected === index ? item.selectedIconPath : item.iconPath} />
					<CoverView style={{color: state.selected === index ? state.selectedColor : state.color}}>
						{item.text}
					</CoverView>
				</CoverView>
			))}
		</CoverView>
	)
}

